/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved.
 */

package com.huawei.idea.share;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;

/**
 * 一个像素服务
 *
 * @author w00415409
 * @since 2021/3/10
 */
public class OnePixelWindowService extends Service {
    private static final int WINDOW_COLOR = Color.TRANSPARENT;

    private static final int WINDOW_SIZE = 1;

    private String TAG = OnePixelWindowService.class.getSimpleName();

    private WindowManager mWindowManager;

    private View mOnePixelView;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "悬浮窗启动。。。 ");
        addOnePixelView();
    }

    private void addOnePixelView() {
        mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        params.format = PixelFormat.RGBA_8888;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
        params.gravity = Gravity.START | Gravity.TOP;
        params.x = 0;
        params.y = 0;
        params.width = WINDOW_SIZE;
        params.height = WINDOW_SIZE;

        mOnePixelView = new View(this);
        mOnePixelView.setBackgroundColor(WINDOW_COLOR);
        mWindowManager.addView(mOnePixelView, params);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        removeOnPixelView();
    }

    private void removeOnPixelView() {
        if (mOnePixelView != null && mWindowManager != null) {
            mWindowManager.removeViewImmediate(mOnePixelView);
            mOnePixelView = null;
        }
    }
}
